/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package su.samlib.informer.database.controllers;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import su.samlib.informer.database.controllers.exceptions.NonexistentEntityException;
import su.samlib.informer.database.controllers.exceptions.PreexistingEntityException;
import su.samlib.informer.database.model.User;
import su.samlib.informer.database.model.Author;
import su.samlib.informer.database.model.UserAuthors;
import su.samlib.informer.database.model.UserAuthorsPK;

/**
 *
 * @author rikland
 */
public class UserAuthorsJpaController implements Serializable {

    public UserAuthorsJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(UserAuthors userAuthors) throws PreexistingEntityException, Exception {
        if (userAuthors.getUserAuthorsPK() == null) {
            userAuthors.setUserAuthorsPK(new UserAuthorsPK());
        }
        userAuthors.getUserAuthorsPK().setUserId(userAuthors.getUser().getUserId());
        userAuthors.getUserAuthorsPK().setAuthorId(userAuthors.getAuthor().getAuthorId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user = userAuthors.getUser();
            if (user != null) {
                user = em.getReference(user.getClass(), user.getUserId());
                userAuthors.setUser(user);
            }
            Author author = userAuthors.getAuthor();
            if (author != null) {
                author = em.getReference(author.getClass(), author.getAuthorId());
                userAuthors.setAuthor(author);
            }
            em.persist(userAuthors);
            if (user != null) {
                user.getUserAuthorsList().add(userAuthors);
                user = em.merge(user);
            }
            if (author != null) {
                author.getUserAuthorsList().add(userAuthors);
                author = em.merge(author);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findUserAuthors(userAuthors.getUserAuthorsPK()) != null) {
                throw new PreexistingEntityException("UserAuthors " + userAuthors + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(UserAuthors userAuthors) throws NonexistentEntityException, Exception {
        userAuthors.getUserAuthorsPK().setUserId(userAuthors.getUser().getUserId());
        userAuthors.getUserAuthorsPK().setAuthorId(userAuthors.getAuthor().getAuthorId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserAuthors persistentUserAuthors = em.find(UserAuthors.class, userAuthors.getUserAuthorsPK());
            User userOld = persistentUserAuthors.getUser();
            User userNew = userAuthors.getUser();
            Author authorOld = persistentUserAuthors.getAuthor();
            Author authorNew = userAuthors.getAuthor();
            if (userNew != null) {
                userNew = em.getReference(userNew.getClass(), userNew.getUserId());
                userAuthors.setUser(userNew);
            }
            if (authorNew != null) {
                authorNew = em.getReference(authorNew.getClass(), authorNew.getAuthorId());
                userAuthors.setAuthor(authorNew);
            }
            userAuthors = em.merge(userAuthors);
            if (userOld != null && !userOld.equals(userNew)) {
                userOld.getUserAuthorsList().remove(userAuthors);
                userOld = em.merge(userOld);
            }
            if (userNew != null && !userNew.equals(userOld)) {
                userNew.getUserAuthorsList().add(userAuthors);
                userNew = em.merge(userNew);
            }
            if (authorOld != null && !authorOld.equals(authorNew)) {
                authorOld.getUserAuthorsList().remove(userAuthors);
                authorOld = em.merge(authorOld);
            }
            if (authorNew != null && !authorNew.equals(authorOld)) {
                authorNew.getUserAuthorsList().add(userAuthors);
                authorNew = em.merge(authorNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                UserAuthorsPK id = userAuthors.getUserAuthorsPK();
                if (findUserAuthors(id) == null) {
                    throw new NonexistentEntityException("The userAuthors with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(UserAuthorsPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserAuthors userAuthors;
            try {
                userAuthors = em.getReference(UserAuthors.class, id);
                userAuthors.getUserAuthorsPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The userAuthors with id " + id + " no longer exists.", enfe);
            }
            User user = userAuthors.getUser();
            if (user != null) {
                user.getUserAuthorsList().remove(userAuthors);
                user = em.merge(user);
            }
            Author author = userAuthors.getAuthor();
            if (author != null) {
                author.getUserAuthorsList().remove(userAuthors);
                author = em.merge(author);
            }
            em.remove(userAuthors);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<UserAuthors> findUserAuthorsEntities() {
        return findUserAuthorsEntities(true, -1, -1);
    }

    public List<UserAuthors> findUserAuthorsEntities(int maxResults, int firstResult) {
        return findUserAuthorsEntities(false, maxResults, firstResult);
    }

    private List<UserAuthors> findUserAuthorsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(UserAuthors.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public UserAuthors findUserAuthors(UserAuthorsPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(UserAuthors.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserAuthorsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<UserAuthors> rt = cq.from(UserAuthors.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
